package com.advert.boot.system.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.advert.boot.common.exception.BusinessException;
import com.advert.boot.common.result.ResultCode;
import com.advert.boot.system.model.entity.AdvertFiles;
import com.advert.boot.system.service.AdvertFileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Objects;

@Tag(name = "12.附件接口")
@RestController
@SuppressWarnings("SpellCheckingInspection")
@RequestMapping("/api/v1/file")
@RequiredArgsConstructor
public class AdvertFileController {
    private final AdvertFileService fileService;

    @Operation(summary = "上传附件接口（支持：png/pdf/jpg/bmp/jpeg）")
    @PostMapping("/upload")
    public ResponseEntity<Long> uploadFile(@RequestParam("file") MultipartFile file) {
        return ResponseEntity.ok(fileService.storeFile(file));
    }

    @Operation(summary = "下载附件接口")
    @GetMapping("/download/{fileId}")
    public void downloadFile(@PathVariable Long fileId, HttpServletResponse response) {
        Assert.isFalse(fileId != null && fileId >= 0, "参数错误，请检查！");

        AdvertFiles fileEntity = fileService.getFile(fileId);
        if (Objects.isNull(fileEntity) || StrUtil.isBlank(fileEntity.getFilePath())) {
            throw new BusinessException(ResultCode.FAILED, "该附件不存在！");
        }

        response.setContentType("application/vnd.ms-word;charset=utf-8");
        try {
            response.setHeader("Content-Disposition",
                    "attachment;filename=\"" + new String(fileEntity.getFileName().getBytes("gb2312"), "ISO8859-1"));
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileEntity.getFilePath()));
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            byte[] bytes = new byte[1024 * 10];
            int len;
            while (-1 != (len = bis.read(bytes))) {
                bos.write(bytes, 0, len);
            }

            bis.close();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}